package com.chorye.mongo.config;

import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

/**
 * @Company: 北京XXXX有限公司
 * @Author JiangYy
 * @Title: MultipleMongoConfig
 * @Description: 读取对应的配置信息并且构造对应的MongoTemplate
 * @Date 2018/12/24 15:58
 */
@Configuration
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties;

    /**
     * 配置主数据源template
     *
     * @return 主数据源template
     */
    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }

    /**
     * 配置从数据源template
     *
     * @return 从数据源template
     */
    @Bean
    @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate secondaryMongoTemplate() {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }

    /**
     * 配置主数据源db工厂
     *
     * @param mongo 属性配置信息
     * @return 主数据源db工厂
     */
    @Bean
    @Primary
    public MongoDbFactory primaryFactory(MongoProperties mongo) {
        return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
                mongo.getDatabase());
    }

    /**
     * 配置从数据源db工厂
     *
     * @param mongo 属性配置信息
     * @return 从数据源db工厂
     */
    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongo) {
        return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
                mongo.getDatabase());
    }
}
